# -*- coding: utf-8 -*-
from django.shortcuts import render

# add by hcq
from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from app_accounts.models import *
from app_TuringClass.models import *
from django.core.exceptions import *
from django import forms
#send e-mail
from django.core.mail import send_mail
# 调用自行编写的lib库
from app_TuringClass.lib_appTuringClass import *
from app_TuringClass.turning_class import *

from django.utils import timezone
import math
import string
import re
import os
import json
import time
import datetime
import base64
# Create your views here.

# Add a patterns so that we can directly open the html pages without the prefix TuringClass/
# author: Xiangyi
# date: 2016/11/15
# delete by houchaoqun 2016 11 18
# def Home_TuringClass(request,page_name="Home_TuringClass"):
# 	return render(request, page_name+'Home_TuringClass.html')

# Add an empty function for HomePage
# author: houchaoqun
# date: 2016/11/20
# @csrf_exempt is for "form"

# @csrf_exempt
# def Home_TuringClass(request):
# 	context = {}
# 	context['sum_test'] = test(request, 10, 20)
# 	return render(request, 'Home_TuringClass.html', context)
'''
@csrf_exempt
def Home_TuringClass(request):

	# update QuestionList
	# _QuestionDetails = QuestionDetails.objects.all()
	# for item in _QuestionDetails:
	# 	if item.QuestionStatus == 'Approved':
	# 		if QuestionList.objects.filter(QuestionID = item.QuestionID).exists():
	# 			pass
	# 		else:
	# 			QuestionList(QuestionID = item.QuestionID, QuestionAbstract = item.QuestionAbstract, QuestionContent = item.QuestionContent).save()
	# 			print "[QuestionID] = ",item.QuestionID
	# 			print "QuestionDetails to QuestionList successful..."
	#
	context = {}
	if request.session.has_key('UserID'):
		context['Login'] = True
	context['Home_active'] = True
	questionSet = QuestionList.objects.all()
	context["questionSet"] = questionSet
	return render(request, 'Home_TuringClass_bound.html', context)
'''
# Add an empty function for Login
# author: houchaoqun
# date: 2016/11/20
# @csrf_exempt
# def Login(request):
# 	context = {}
# 	context['Login_active'] = True
# 	return render(request, 'Login.html', context)

# @csrf_exempt
# def Regist(request):
# 	context = {}
# 	return render(request, 'Regist.html', context)

# Add an empty function for Tags
# author: houchaoqun
# date: 2016/11/20
@csrf_exempt
def Tags(request):
	context = {}
	if request.session.has_key('UserID'):
		context['Login'] = True
	tags=QuestionTag.objects.all()
	uls=[]
	for i in range(0,(len(tags)-1)/3+1):
		ul=[]
		j=0
		while i*3+j<len(tags) and j<3:
			ul.append(tags[i*3+j].TagName)
			j+=1
		uls.append(ul)
	context['uls']=uls
	context['QuestionTag_active'] = True
	return render(request, 'Tags.html', context)

# Add an empty function for Help
# author: houchaoqun
# date: 2016/11/20
@csrf_exempt
def HelpContent(request):
	context = {}
	if request.session.has_key('UserID'):
		context['Login'] = True

	context['Help_active'] = True
	return render(request, 'HelpContent.html', context)

# Add an empty function for DownloadArea
# author: houchaoqun
# date: 2016/11/20
@csrf_exempt
def DownloadArea(request):
	context = {}
	if request.session.has_key("UserID"):
		UserID = request.session.get("UserID")
		user = TuringUser.objects.get(UserID=UserID)
		role = TuringRoleType.objects.get(RoleTypeID=user.RoleTypeID)
		if role.SuperPermission:
			SuperPermission = 1
		else:
			SuperPermission = 0
		context['super'] = SuperPermission
		context['Login'] = True
	else:
		context['super'] = 0
		context['Login'] = False
	List = UploadingFiles.objects.all()
	context['DownLoadArea_active'] = True
	context['fileList'] = List
	# context = {'fileList':List,'super':SuperPermission}
	return render(request, 'DownloadArea.html', context)


# Add an empty function for Question
# author: houchaoqun
# date: 2016/11/20
@csrf_exempt
def Question(request):
	context = {}
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect("/Accounts/login/")
		# return HttpResponse('请先登录，再进行提问!')
	else:
		context['Login'] = True
	tags=QuestionTag.objects.all()
	uls=[]
	for i in range(0,(len(tags)-1)/8+1):
		ul=[]
		j=0
		while i*8+j<len(tags) and j<8:
			ul.append(tags[i*8+j].TagName)
			j+=1
		uls.append(ul)
	context['uls']=uls

	context['Question_active'] = True
	return render(request, 'Question.html', context)

@csrf_exempt
def Home_TuringClass(request):
	context = {}
	allUser = TuringUser.objects.all().order_by('-UserPoints')[0:5]
	context['topUser'] = allUser
	if request.session.has_key('UserID'):
		context['Login'] = True
	context['Home_active'] = True
	questionList = QuestionList.objects.all().order_by('-LastModifyDate')
	questionSet=[]
	for question in questionList:
		q={}
		tags=question.TagsID.split(";")
		tagsName=[]
		if len(tags[0])!=0:
			for tag in tags:
				t=QuestionTag.objects.get(TagID=tag)
				tagsName.append(t.TagName)
		q['tags']=tagsName
		q['BrowseNum']=question.BrowseNum
		q['PraiseNum']=question.PraiseNum
		q['AnswerNum']=question.AnswerNum
		q['QuestionAbstract']=question.QuestionAbstract
		q['QuestionID']=question.QuestionID
		q['AskDate']=timeDelta(question.QuestionCreateDate,'提问')
		q['askDate'] = question.QuestionCreateDate
		q['QuizzerName'] = question.QuizzerName
		questionSet.append(q)
	context["questionSet"] = questionSet
	context['news'] = News.objects.all().order_by('-Priority', '-CreateDate')
	return render(request, 'Home_TuringClass.html', context)
#Use send_mail('subject','message','fromname<from-mail>',['<to-mail>'],fail_silently = False) to send e-mail when needed.

@csrf_exempt
def QuestionDelete(request):
	if request.POST:
		if not request.session.has_key('UserID'):
			return HttpResponse(json.dumps("/Accounts/login/"))
		QuestionID = request.POST['QuestionID']
		UserID = request.session.get('UserID')
		try:
			q = QuestionDetails.objects.get(QuestionID = QuestionID)
			question = QuestionList.objects.get(QuestionID = QuestionID)
		except:
			return HttpResponse(json.dumps('error'))
		else:
			if question.QuizzerID == UserID:
				q.delete()
				QuestionAnswers.objects.filter(QuestionID = QuestionID).delete()
				focus = question.FocusByUserID.split(';')
				for ID in focus:
					user = TuringUser.objects.get(UserID = ID)
					f = user.QuestionString.split(';')
					f.remove(QuestionID)
					user.QuestionString = ';'.join(f)
					user.save()
				question.delete()
				return HttpResponse(json.dumps('/'))
			else:
				return HttpResponse(json.dumps('error'))
	return HttpResponse('Whoops!')

@csrf_exempt
def NewsSubmit(request):
	if not request.session.has_key('UserID'):
		return HttpResponse('请先登录')
	if request.POST:
		UserID = request.session.get('UserID')
		user = TuringUser.objects.get(UserID = UserID)
		Title = request.POST.get('title')
		Content = request.POST.get('post-text')
		try:
			highpoints = re.compile(u'[\U00010000-\U0010ffff]')
		except re.error:
			highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
		Title = highpoints.sub(u'\u25FD',Title)
		Content = highpoints.sub(u'\u25FD', Content)
		return HttpResponse('ok')
	return HttpResponse('Whoops!')

@csrf_exempt
def AskSubmit(request):
	context = {}
	if not request.session.has_key('UserID'):
		return HttpResponse('请先登录，再进行提问')
	context['Question_active'] = True
	if request.method == "POST":
		UserID=request.session.get('UserID')
		user=TuringUser.objects.get(UserID=UserID)
		QuestionAbstract = request.POST.get('title')
		QuestionContent = request.POST.get('post-text')
		try:
			highpoints = re.compile(u'[\U00010000-\U0010ffff]')
		except re.error:
			highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
		QuestionAbstract = highpoints.sub(u'\u25FD',QuestionAbstract)
		QuestionContent = highpoints.sub(u'\u25FD', QuestionContent)
		tags=request.POST.get('tags').split(', ')
		tagID=[]
		if tags[0]!="":
			for tag in tags:
				if QuestionTag.objects.filter(TagName = tag).exists():
					t = QuestionTag.objects.get(TagName=tag)
					tagID.append(t.TagID)
		TagID=";".join(tagID)
		QD_QuestionID = str(int(QuestionDetails.objects.raw('SELECT * FROM app_TuringClass_questiondetails ORDER BY QuestionID DESC LIMIT 1')[0].QuestionID)+1)
		focus=UserID
		if user.QuestionString:
			userFocus=user.QuestionString.split(";")
			userFocus.append(QD_QuestionID)
			user.QuestionString=";".join(userFocus)
		else:
			user.QuestionString=QD_QuestionID
		user.save()
		QuestionDetails(TagsID=TagID, QuizzerID=UserID, QuestionID = QD_QuestionID, QuestionAbstract = QuestionAbstract, QuestionContent = QuestionContent, QuestionStatus='Approved').save()
		QuestionList(LastModifyDate=timezone.now(),FocusByUserID=focus,TagsID=TagID,QuizzerName=user.NickName, QuizzerID=UserID,QuestionID =QD_QuestionID, QuestionAbstract = QuestionAbstract, QuestionContent = QuestionContent).save()
		allUser = TuringUser.objects.filter(RoleTypeID = 'volunteer')
		#print allUser
		userToEmail = []
		for u in allUser:
			if not u.EnshrineString:
				continue
			focusTag = u.EnshrineString.split(';')
			for t in tagID:
				if t in focusTag:
					userToEmail.append(u.UserEmail)
					break
		for email in userToEmail:
			try:
				# send_mail('Attention: There is a new question!!!','Question:\n [ ' + QuestionAbstract + ' ] has been asked. Please Check it as soon as fast.\n  http://127.0.0.1:8000/QuestionDetails/?id=' + QD_QuestionID, 'TuringClass<13276022792@sina.cn>', [ '<3345947441@qq.com>'], fail_silently = False)
				send_mail('Attention: There is a new question!!!','Question:\n [ ' + QuestionAbstract +' ] has been asked. Please Check it as soon as fast. [' + UserID + '] \n  http://turing.ymyin.me/QuestionDetails/?id=' + str(QD_QuestionID), 'TuringClass<13276022792@sina.cn>', [ email ], fail_silently = False)
				# send_mail('[志愿者请注意]: 图灵课程线上系统有个新问题等待您去解决!!!','\n 问题[ ' + QuestionAbstract +' ]已被提问. 请尽快前往解答.\n  http://127.0.0.1:8000/QuestionDetails/?id='+str(QD_QuestionID),'TuringClass<13276022792@sina.cn>', [ '<3345947441@qq.com>'], fail_silently = False)
				# try:
				# 	fo_Success = open(".\\app_TuringClass\Email_Success.log", "wb")
				# 	EmailContent = '[ ' + QuestionAbstract + ' ] has been asked. Link = http://127.0.0.1:8000/QuestionDetails/?id=' + QD_QuestionID + '\n'
				# 	fo_Success.write(EmailContent)
				# except IOError:
				# 	print "Error: 没有找到文件或读取文件失败"
	   			# else:
	   			# 	fo_Success.close()
			except:
				# print "[Failure] send_mail() - [ ", QuestionAbstract , "]"
				try:
					print "fo_Failure = open('.／Email_Failure.log', 'a')"
					# fo_Failure = open(".／Email_Failure.log", "a")
					# write, 如果文件存在，则会首先清空，然后写入, 设置文件打开的方式为'a'，表示将打开追加文件。文件指针是在文件的结尾。也就是说，该文件是在附加模式。如果该文件不存在，它创造了写入一个新的文件
					# EmailContent = '[Failuer] - ( ' + QuestionAbstract + ' ) has been asked. Link = http://127.0.0.1:8000/QuestionDetails/?id=' + QD_QuestionID + '\n'
					# fo_Failure.writelines('[Failure] - ( ' + QuestionAbstract + ' ) has been asked. Link = http://turing.ymyin.me/QuestionDetails/?id=' + QD_QuestionID + 'send to ' + email + '\n')
				except IOError:
					print "Error: 没有找到文件或读取文件失败"
    			else:
    				print "fo_Failure.close()"
    				# fo_Failure.close()
			finally:
				pass
		UpdateUserPoint(UserID)
		return HttpResponseRedirect('/QuestionDetails/?id=' + str(QD_QuestionID))
	return HttpResponse("Whoops!")

def timeDelta(dateTime, string):
	time=dateTime.replace(tzinfo=None)
	delta=datetime.datetime.utcnow()-time
	if delta.days>0:
		timedelta = dateTime.replace(tzinfo = None)
#		if delta.days==1:
#			timedelta=str(delta.days)+" day ago"
#		else:
#			timedelta=str(delta.days)+" days ago"
	else:
		if delta.seconds>3600:
			if delta.seconds<7200:
				timedelta="1小时前" + string
			else:
				timedelta=str(delta.seconds/3600)+"小时前" + string
		else:
			if delta.seconds>60:
				if delta.seconds<120:
					timedelta="1分钟前提问"
				else:
					timedelta=str(delta.seconds/60)+"分钟前" + string
			else:
				if delta.seconds<=1:
					timedelta="1秒前" + string
				else:
					timedelta=str(delta.seconds)+"秒前" + string
	return timedelta

def showQuestionDetail(request, ID):
	if request.session.has_key('UserID'):
		UserID = request.session.get('UserID')
	else:
		UserID = ''
	detail = QuestionList.objects.get(QuestionID = ID)
	if detail.QuizzerID == UserID:
		Owned = 1
	else:
		Owned = 0
	timedelta = timeDelta(detail.QuestionCreateDate, '提问')
	if not detail:
		return HttpResponse("Whoops!")
	else:
		detail.BrowseNum += 1
		detail.save()
		answers = QuestionAnswers.objects.filter(QuestionID = ID).order_by("-PraiseNum")
		Answers = []
		for answer in answers:
			Answer = {}
			Answer['ResponderName'] = answer.ResponderName
			Answer['AnswerContent'] = answer.AnswerContent
			Answer['PraiseNum'] = answer.PraiseNum
			Answer['OpposeNum'] = answer.OpposeNum
			Answer['answerTime'] = timeDelta(answer.AnswerDate, '回答')
			Answer['AnswerID'] = answer.AnswerID
			Answer['avatar'] = getAvatar(answer.ResponderID)
			Answer['IsAccepted'] = answer.IsAccepted
			if answer.ResponderID == UserID:
				Answer['Owned'] = 1
			else:
				Answer['Owned'] = 0
			if answer.IsAccepted:
				Answers.insert(0, Answer)
			else:
				Answers.append(Answer)
		tagName = []
		if len(detail.TagsID) != 0:
			tags=detail.TagsID.split(";")
			for tag in tags:
				name=QuestionTag.objects.get(TagID=tag).TagName
				tagName.append(name)
		context={
			'questionTime':timedelta,
			'question': detail,
			'answers': Answers,
			'tags': tagName,
			'Owned': Owned,
			'avatar': getAvatar(detail.QuizzerID),
			}
		if request.session.has_key('UserID'):
			context['Login'] = True
		return context

@csrf_exempt
def AnswerDelete(request):
	if request.POST:
		if not request.session.has_key('UserID'):
			return HttpResponse(json.dumps("/Accounts/login/"))
		AnswerID = request.POST['AnswerID']
		UserID = request.session.get('UserID')
		try:
			answer = QuestionAnswers.objects.get(AnswerID = AnswerID)
			question = QuestionList.objects.get(QuestionID = answer.QuestionID)
		except Exception as e:
			return HttpResponse(json.dumps('error'))
		else:
			if answer.ResponderID == UserID:
				question.AnswerNum -= 1
				question.save()
				answer.delete()
				return HttpResponse(json.dumps('/QuestionDetails/?id=' + str(answer.QuestionID)))
			else:
				return HttpResponse(json.dumps('error'))
	return HttpResponse('Whoops!')

@csrf_exempt
def AnswerSubmit(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect("/Accounts/login/")
	if request.method=="POST":
		Content = request.POST.get('post-text')
		try:
			highpoints = re.compile(u'[\U00010000-\U0010ffff]')
		except re.error:
			highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
		Content = highpoints.sub(u'\u25FD',Content)
		questionID=request.POST.get('qID')
		respondentID=request.session.get('UserID')
		user=TuringUser.objects.get(UserID=respondentID)
		respondentName=user.NickName
		answerID=time.strftime("%Y%m%d%H%M%S", time.gmtime())
		try:
			question=QuestionList.objects.get(QuestionID=questionID)
		except:
			return HttpResponse('Whoops!')
		else:
			QuestionAnswers(
				AnswerContent=Content,
				QuestionID=questionID,
				AnswerID=answerID + '_' + respondentID,
				ResponderID=respondentID,
				ResponderName=respondentName).save()
			question.AnswerNum+=1;
			question.LastModifyDate=timezone.now()
			flag=0
			if question.FocusByUserID:
				List=question.FocusByUserID.split(";")
				for l in List:
					if user.UserID==l:
						flag=1
			else:
				List=[]
			if flag==0 and request.POST.has_key('receive_email'):
				List.append(user.UserID)
				f=";".join(List)
				question.FocusByUserID=f
				if user.QuestionString:
					qList=user.QuestionString.split(";")
				else:
					qList=[]
				qList.append(questionID)
				q=";".join(qList)
				user.QuestionString=q
				user.save()
			question.save()
#			for l in List:
#				if user.UserID!=l:
#					u=TuringUser.objects.get(UserID=l)
#					try:
#						send_mail('TuringClass: New answer for the Question!!!','Question:\n [ ' + question.QuestionAbstract +' ] has been replied. \n  http://turing.ymyin.me/QuestionDetails/?id='+questionID,'TuringClass<13276022792@sina.cn>', [ u.UserEmail ], fail_silently = False)
#					except:
#						try:
#							print "try successful..."
#							# fo_Failure = open(".／Email_Failure.log", "a")
#							# fo_Failure.writelines('[Failure] - ( ' + question.QuestionAbstract + ' ) has been replied. Link = http://turing.ymyin.me/QuestionDetails/?id=' + questionID + '\n' + '[ e-mail = ' + u.UserEmail + ']')
#						except IOError:
#							print "Error: 没有找到文件或读取文件失败"
#						else:
#							print "fo_Failure.close()"
							# fo_Failure.close()
#					finally:
#						pass
			u = TuringUser.objects.get(UserID = question.QuizzerID)
			try:
				send_mail('TuringClass: New answer for the Question!!!','Question:\n [ ' + question.QuestionAbstract +' ] has been replied. \n  http://turing.ymyin.me/QuestionDetails/?id='+questionID,'TuringClass<13276022792@sina.cn>', [ u.UserEmail ], fail_silently = False)
			except:
				try:
					print "try successful..."
					# fo_Failure = open(".／Email_Failure.log", "a")
					# fo_Failure.writelines('[Failure] - ( ' + question.QuestionAbstract + ' ) has been replied. Link = http://turing.ymyin.me/QuestionDetails/?id=' + questionID + '\n' + '[ e-mail = ' + u.UserEmail + ']')
				except IOError:
					print "Error: 没有找到文件或读取文件失败"
				else:
					print "fo_Failure.close()"
					# fo_Failure.close()
			finally:
				pass
			UpdateUserPoint(respondentID)
			return HttpResponseRedirect('/QuestionDetails/?id='+questionID)
	return HttpResponse('Whoops!')


@csrf_exempt
def QuestionDetailsView(request):
	if request.method=="GET":
		ID=str(request.GET.get('id'))
		try:
			QuestionList.objects.get(QuestionID = ID)
		except:
			return HttpResponseRedirect('/')
		context=showQuestionDetail(request, ID)
		if request.session.has_key('UserID'):
			user=TuringUser.objects.get(UserID=request.session.get('UserID'))
			if user.QuestionString:
				qstring=user.QuestionString.split(";")
				for s in qstring:
					if s==ID:
						context['Liked']=True
		return render(request,'QuestionDetails.html',context)

def GetFileNameAndExt(filename):
	(filepath,tempfilename) = os.path.split(filename);
	(shotname,extension) = os.path.splitext(tempfilename);
	return shotname,extension

def saveFile(file,UserID):
	user=TuringUser.objects.get(UserID=UserID)
	role=TuringRoleType.objects.get(RoleTypeID=user.RoleTypeID)
	if not role.SuperPermission:
		return "Action denied!"
	filename,filetype=GetFileNameAndExt(file.name)
	file.name=filename + "_" + time.strftime("%Y%m%d_%H%M%S", time.gmtime()) + '_' + user.NickName + filetype
	File=UploadingFiles.objects.filter(FileName=file.name)
	if not File:
		UploadingFiles(FileName=file.name).save()
	else:
		i=1
		File=UploadingFiles.objects.filter(FileName="dif"+"_"+str(i)+"_"+file.name)
		while File:
			i+=1
			File=UploadingFiles.objects.filter(FileName="dif"+"_"+str(i)+"_"+file.name)
		file.name="dif"+"_"+str(i)+"_"+file.name
	try:
		destination = open("./app_TuringClass/Documents_Upload/"+file.name,'wb+')
		for chunk in file.chunks():
			destination.write(chunk)
		destination.close()
	except Exception as e:
		print e
		return "Upload fail"
	else:
		return "Upload over"

@csrf_exempt
def Upload(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/Accounts/login/')
	if request.method == "POST":
		UserID=request.session.get('UserID')
		myFile =request.FILES.getlist("Filedata", None)
		if not myFile:
			return HttpResponse("no files for upload!")
		for file in myFile:
			info=saveFile(file,UserID)
		return HttpResponse(info)

@csrf_exempt
def DeleteFile(request):
	dic = {'info':'ok'}
	if request.method == 'POST':
		path=request.POST.get('file')
		UploadingFiles.objects.filter(FileName=path).delete()
        target=os.path.join('./app_TuringClass/Documents_Upload/',path)
        os.remove(target)
        data=json.dumps(dic)
        return HttpResponse(json.dumps(data))
	return HttpResponse('Whoops!')

def CheckFile(request):
	filename = request.GET.get('file')
	print filename
	if not os.path.exists("./app_TuringClass/Documents_Upload/" + filename):
		print 'aaa'
		UploadingFiles.objects.filter(FileName = filename).delete()
		return HttpResponse(json.dumps('fail'))
	else:
		return HttpResponse(json.dumps('ok'))

def DownloadFile(request):
    filename_=request.GET.get('file')
    filepath_=os.path.join("./app_TuringClass/Documents_Upload/",filename_)
    def readFile(fn, buf_size=262144):
        f = open(fn, "rb")
        while True:
            c = f.read(buf_size)
            if c:
                yield c
            else:
                break
        f.close()
    file=UploadingFiles.objects.get(FileName=filename_)
    file.DownloadNum += 1
    file.save()
    response = StreamingHttpResponse(readFile(filepath_), content_type='APPLICATION/OCTET-STREAM')
    response['Content-Disposition'] = 'attachment; filename='+filename_.encode('utf-8')
    response['Content-Length'] = os.path.getsize(filepath_)
    return response

def QuestionPraise(request):
	dic = {}
	if not request.session.has_key('UserID'):
		dic={'info':'please login first!'}
		data=json.dumps(dic)
		return HttpResponse(data)
	userID=request.session.get('UserID')
	ID=request.GET.get('id')
	try:
		question=QuestionList.objects.get(QuestionID=ID)
	except:
		dic={'info':'failed'}
		data=json.dumps(dic)
		return HttpResponse(data)
	else:
		if question.NonSupportByUserID:
			opposers=question.NonSupportByUserID.split(";")
			for opposer in opposers:
				if userID==opposer:
					opposers.remove(userID)
					question.OpposeNum -= 1
					if question.OpposeNum:
						question.NonSupportByUserID = ";".join(opposers)
					else:
						question.NonSupportByUserID = ""
					question.save()
					dic['opposeNum'] = question.OpposeNum
					break
		if question.SupportByUserID:
			praisers=question.SupportByUserID.split(";")
			for praiser in praisers:
				if userID==praiser:
					dic['info'] = question.PraiseNum
					data=json.dumps(dic)
					return HttpResponse(data)
		else:
			praisers=[]
		praisers.append(userID)
		p=";".join(praisers)
		question.SupportByUserID=p
		question.PraiseNum+=1
		question.save()
		dic['info'] = question.PraiseNum
		data=json.dumps(dic)
		UpdateUserPoint(question.QuizzerID)
        return HttpResponse(data)

def QuestionOppose(request):
	dic = {}
	if not request.session.has_key('UserID'):
		dic={'info':'please login first!'}
		data=json.dumps(dic)
		return HttpResponse(data)
	userID=request.session.get('UserID')
	ID=request.GET.get('id')
	try:
		question=QuestionList.objects.get(QuestionID=ID)
	except:
		dic={'info':'failed'}
		data=json.dumps(dic)
		return HttpResponse(data)
	else:
		if question.SupportByUserID:
			praisers=question.SupportByUserID.split(";")
			for praiser in praisers:
				if userID==praiser:
					praisers.remove(userID)
					question.PraiseNum -= 1
					if question.PraiseNum:
						question.SupportByUserID = ";".join(praisers)
					else:
						question.SupportByUserID = ""
					dic['praiseNum'] = question.PraiseNum
					question.save()
					break
		if question.NonSupportByUserID:
			opposers=question.NonSupportByUserID.split(";")
			for opposer in opposers:
				if userID==opposer:
					dic['info'] = question.OpposeNum
					data=json.dumps(dic)
					return HttpResponse(data)
		else:
			opposers=[]
		opposers.append(userID)
		o=";".join(opposers)
		question.NonSupportByUserID=o
		question.OpposeNum+=1
		question.save()
		dic['info'] = question.OpposeNum
		data=json.dumps(dic)
		UpdateUserPoint(question.QuizzerID)
        return HttpResponse(data)

def AnswerPraise(request):
	dic = {}
	if not request.session.has_key('UserID'):
		dic={'info':'please login first!'}
		data=json.dumps(dic)
		return HttpResponse(data)
	userID=request.session.get('UserID')
	ID=request.GET.get('id')
	try:
		answer=QuestionAnswers.objects.get(AnswerID=ID)
	except:
		dic={'info':'failed'}
		data=json.dumps(dic)
		return HttpResponse(data)
	else:
		if answer.NonSupportByUserID:
			opposers=answer.NonSupportByUserID.split(";")
			for opposer in opposers:
				if userID==opposer:
					opposers.remove(userID)
					answer.OpposeNum -= 1
					if answer.OpposeNum:
						answer.NonSupportByUserID = ";".join(opposers)
					else:
						answer.NonSupportByUserID = ""
					answer.save()
					dic['opposeNum'] = answer.OpposeNum
					break
		if answer.SupportByUserID:
			praisers=answer.SupportByUserID.split(";")
			for praiser in praisers:
				if userID==praiser:
					dic['info'] = answer.PraiseNum
					data=json.dumps(dic)
					return HttpResponse(data)
		else:
			praisers=[]
		praisers.append(userID)
		p=";".join(praisers)
		answer.SupportByUserID=p
		answer.PraiseNum+=1
		answer.save()
		dic['info'] = answer.PraiseNum
		data=json.dumps(dic)
		UpdateUserPoint(answer.ResponderID)
        return HttpResponse(data)

def AnswerOppose(request):
	dic = {}
	if not request.session.has_key('UserID'):
		dic={'info':'please login first!'}
		data=json.dumps(dic)
		return HttpResponse(data)
	userID=request.session.get('UserID')
	ID=request.GET.get('id')
	try:
		answer=QuestionAnswers.objects.get(AnswerID=ID)
	except:
		dic={'info':'failed'}
		data=json.dumps(dic)
		return HttpResponse(data)
	else:
		if answer.SupportByUserID:
			praisers=answer.SupportByUserID.split(";")
			for praiser in praisers:
				if userID==praiser:
					praisers.remove(userID)
					answer.PraiseNum -= 1
					if answer.PraiseNum:
						answer.SupportByUserID = ";".join(praisers)
					else:
						answer.SupportByUserID = ""
					answer.save()
					dic['praiseNum'] = answer.PraiseNum
					break
		if answer.NonSupportByUserID:
			opposers=answer.NonSupportByUserID.split(";")
			for opposer in opposers:
				if userID==opposer:
					dic['info'] = answer.OpposeNum
					data=json.dumps(dic)
					return HttpResponse(data)
		else:
			opposers=[]
		opposers.append(userID)
		o=";".join(opposers)
		answer.NonSupportByUserID=o
		answer.OpposeNum+=1
		answer.save()
		dic['info'] = answer.OpposeNum
		data=json.dumps(dic)
		UpdateUserPoint(answer.ResponderID)
        return HttpResponse(data)

def like_it(request):
	if not request.session.has_key('UserID'):
		dic={'info':'please login first!'}
		data=json.dumps(dic)
		return HttpResponse(data)
	userID=request.session.get('UserID')
	user=TuringUser.objects.get(UserID=userID)
	ID=request.GET.get('id')
	try:
		question=QuestionList.objects.get(QuestionID=ID)
	except:
		dic={'info':'failed'}
		data=json.dumps(dic)
		return HttpResponse(data)
	else:
		if question.FocusByUserID:
			List=question.FocusByUserID.split(";")
			for l in List:
				if userID==l:
					List.remove(userID)
					f=";".join(List)
					question.FocusByUserID=f
					question.save()
					qList=user.QuestionString.split(";")
					qList.remove(ID)
					q=";".join(qList)
					user.QuestionString=q
					user.save()
					dic={'info':"disliked"}
					data=json.dumps(dic)
					UpdateUserPoint(question.QuizzerID)
					return HttpResponse(data)
		else:
			List=[]
		List.append(userID)
		f=";".join(List)
		question.FocusByUserID=f
		question.save()
		if user.QuestionString:
			qList=user.QuestionString.split(";")
		else:
			qList=[]
		qList.append(ID)
		q=";".join(qList)
		user.QuestionString=q
		user.save()
		dic={'info':"liked"}
		data=json.dumps(dic)
		UpdateUserPoint(question.QuizzerID)
		return HttpResponse(data)

def getAvatar(UserID):
	if not os.path.exists('./static/upload/' + UserID):
		return '/static/image/111.png'
	file_name = "static/upload/" + UserID
	try:
		des = open(file_name, "r")
		p = des.read()
		des.close()
		p = p[0:4] + ":" + p [7:12] + "/" + p[15:]
		for i in range(len(p)):
			if p[i] == '%':
					p = p[0:i] + ";" + p[i+3:]
					break
		for i in range(len(p)):
			if p[i] == '%':
					p = p[0:i] + "," + p[i+3:]
					break
		return p
	except Exception,e:
		print e
		return ""

def UpdateUserPoint(UserID):
	q = QuestionList.objects.filter(QuizzerID=UserID)
	a = QuestionAnswers.objects.filter(ResponderID=UserID)
	questionNum = len(q)
	answerNum = len(a)
	praiseNum=0
	for _q in q:
		praiseNum += _q.PraiseNum
	for _a in a:
		praiseNum += _a.PraiseNum
	user = TuringUser.objects.get(UserID = UserID)
	user.UserPoints = int(math.ceil(praiseNum * 0.5 + answerNum * 0.3 + questionNum * 0.2))
	user.save()

def PersonalInfo(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect("/Accounts/login/")
		#return HttpResponse('请先登录！')
	UserID=request.session.get('UserID')
	q=QuestionList.objects.filter(QuizzerID=UserID)
	a=QuestionAnswers.objects.filter(ResponderID=UserID)
	questionNum=len(q)
	answerNum=len(a)
	praiseNum=0
	for _q in q:
		praiseNum+=_q.PraiseNum
	for _a in a:
		praiseNum+=_a.PraiseNum
	user=TuringUser.objects.get(UserID=UserID)
	user.UserPoints = int(math.ceil(praiseNum * 0.5 + answerNum * 0.3 + questionNum * 0.2))
	user.save()
	lastLogin=user.LastLoginTime
	if user.QuestionString:
		questionString=user.QuestionString.split(";")
	else:
		questionString=[]
	List=[]
	gather={}
	# changed QuestionList to QuestionDetails by hcq..
	for questionID in questionString:
		question=QuestionDetails.objects.get(QuestionID=questionID)
		abstract=question.QuestionAbstract
		gather['questionID']=question.QuestionID
		gather['questionAbstract']=abstract
		answers=QuestionAnswers.objects.filter(QuestionID=questionID,AnswerDate__gt=lastLogin).order_by('-AnswerDate')#raw("select * from app_turingclass_questionanswers where QuestionID=questionID ")
		for answer in answers:
			if answer.ResponderID != UserID:
				gather['date']=answer.AnswerDate
				List.append(gather)
				break
	List.sort(key=lambda x:x['date'],reverse=True)
	context = {'praiseNum':praiseNum,'questionNum':questionNum,'answerNum':answerNum,'list':List,'user':user}
	context['avatar'] = getAvatar(UserID)
	context['point'] = user.UserPoints
	context['Login'] = True
	context['Personal_active'] = True
	Tags = user.EnshrineString
	uls = []
	if not Tags:
		context['tags'] = ""
		return render(request,'PersonalInfo.html', context)
	tags=Tags.split(";")
	context['tags'] = tags
	return render(request,'PersonalInfo.html', context)


@csrf_exempt
def ModifyEmail(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/Accounts/login/')
	if request.method=="POST":
		email=request.POST.get('email')
		userID=request.session.get('UserID')
		user=TuringUser.objects.get(UserID=userID)
		user.UserEmail=email
		user.save()
		context={'email':email}
		data=json.dumps(context)
		return HttpResponse(data)
	return HttpResponse('Whoops!')

@csrf_exempt
def ModifyQQ(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/Accounts/login/')
	if request.method=="POST":
		qq=request.POST.get('qq')
		userID=request.session.get('UserID')
		user=TuringUser.objects.get(UserID=userID)
		user.UserQQ=qq
		user.save()
		context={'qq':qq}
		data=json.dumps(context)
		return HttpResponse(data)
	return HttpResponse('Whoops!')

@csrf_exempt
def ModifyTelephone(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/Accounts/login/')
	if request.method=="POST":
		telephone=request.POST.get('telephone')
		userID=request.session.get('UserID')
		user=TuringUser.objects.get(UserID=userID)
		user.MobilePhone=telephone
		user.save()
		context={'telephone':telephone}
		data=json.dumps(context)
		return HttpResponse(data)
	return HttpResponse('Whoops!')

@csrf_exempt
def ModifyData(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/Accounts/login/')
	if request.method=="POST":
		qq=request.POST.get('qq')
		telephone=request.POST.get('telephone')
		userID=request.session.get('UserID')
		user=TuringUser.objects.get(UserID=userID)
		user.UserQQ=qq
		user.MobilePhone=telephone
		user.save()
		return HttpResponseRedirect("/PersonalInfo/")
	return HttpResponse('Whoops!')

@csrf_exempt
def UploadIMG(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/Accounts/login/')
	if request.method == 'POST':
		callback = request.GET.get('CKEditorFuncNum')
		try:
			path = "static/upload/"
			f = request.FILES["upload"]
			n,e=GetFileNameAndExt(f.name)
			file_name = path+request.session.get('UserID')+"_"+time.strftime("%Y%m%d_%H%M%S", time.gmtime())+e
			des_origin_f = open(file_name, "wb+")
			for chunk in f.chunks():
				des_origin_f.write(chunk)
			des_origin_f.close()
		except Exception, e:
			print e
		res = "<script>window.parent.CKEDITOR.tools.callFunction("+callback+",'/"+file_name+"', '');</script>"
		return HttpResponse(res)
	else:
		raise Http404()

def AppointmentPage(request):
	context = {}
	if not request.session.has_key('UserID'):
		context['Login'] = False
		context['super'] = 0
	else:
		context['Login'] = True
		user = TuringUser.objects.get(UserID = request.session.get('UserID'))
		context['MobilePhone'] = user.MobilePhone if user.MobilePhone else ''
		context['UserQQ'] = user.UserQQ if user.UserQQ else ''
		context['Name'] = user.NickName
		role = TuringRoleType.objects.get(RoleTypeID=user.RoleTypeID)
		if role.SuperPermission:
			SuperPermission = 1
		else:
			SuperPermission = 0
		context['super'] = SuperPermission
	if request.method == 'GET':
		dates = AvailableDate.objects.filter(IsFinished = 0)
		Dates = []
		for date in dates:
			Date = {}
			Date['Abstract'] = date.activityAbstract
			Date['StartTime'] = date.StartTime
			Date['EndTime'] = date.EndTime
			Date['Limit'] = date.Limit
			Date['Number'] = date.Number
			Date['DateID'] = date.DateID
			Dates.append(Date)
		context['AvailableDates'] = Dates
		#appointments = Appointment.objects.filter(UserID = user.UserID)
		appointments = Appointment.objects.filter(InQueue = 1)
		# print appointments
		Appointments = []
		for appointment in appointments:
			Appointment_ = {}
			length = len(appointment.StudentNum)
			Appointment_['StudentNum'] = appointment.StudentNum
			Appointment_['StudentNum_hide'] = appointment.StudentNum[0:3] + (length - 7) * '*' + appointment.StudentNum[length-4:]
			Appointment_['AppointmentDate'] = appointment.AppointmentDate
			Appointment_['SequenceNumber'] = appointment.SequenceNumber
			length = len(appointment.Name)
			Appointment_['Name'] = appointment.Name
			Appointment_['Name_hide'] = appointment.Name[0:1] + (length - 1) * '*'
			Appointment_['Detail'] = appointment.Detail
			Appointment_['MobilePhone'] = appointment.MobilePhone
			Appointment_['UserQQ'] = appointment.UserQQ
			Appointment_['School'] = appointment.School
			if AvailableDate.objects.filter(DateID = appointment.DateID).exists():
				Appointment_['activityAbstract'] = AvailableDate.objects.get(DateID = appointment.DateID).activityAbstract
			else:
				Appointment_['activityAbstract'] = "None"
			Appointments.append(Appointment_)
		context['Appointments'] = Appointments

		academyInfo = get_academyInfo()
		context['academyInfo'] = academyInfo
		# add by hcq 20170316 - show the info in table
		context['AppointmentInfo_Completed'] = get_AppointmentInfo_Completed(request)
		return render(request, 'AppointmentPage.html', context)
	else:
		return HttpResponse('Whoops!')

def get_academyInfo():
	return ['厦大教职工','人文学院','新闻传播学院','外文学院','艺术学院','国学研究院','海外教育学院','国际学院','经济学院','王亚南经济研究院','管理学院','法学院','财务管理与会计研究院','厦门国际法高等研究院','知识产权研究院','公共事务学院','公共政策研究院','马克思主义学院','国际关系学院','教育研究院','台湾研究院','南洋研究院','海峡两岸发展研究院','体育教学部',
			'继续教育学院','南海研究院','两岸关系和平发展协同创新中心','高等教育质量建设协同创新中心','数学科学学院','物理科学与技术学院','化学化工学院','能源材料化学协同创新中心','信息科学与技术学院','软件学院','材料学院','能源学院','建筑与土木工程学院','航空航天学院','生命科学学院','公共卫生学院','药学院','医学院','生物医学研究院','海洋与地球学院','环境与生态学院','其他']
	# return ['人文学院','新闻传播学院','外文学院','艺术学院','国学研究院','海外教育学院','国际学院','经济学院','王亚南经济研究院','管理学院','法学院','财务管理与会计研究院','厦门国际法高等研究院','知识产权研究院','公共事务学院','公共政策研究院','马克思主义学院','国际关系学院','教育研究院','台湾研究院','南洋研究院','海峡两岸发展研究院','体育教学部',
	# 		'继续教育学院','南海研究院','两岸关系和平发展协同创新中心','高等教育质量建设协同创新中心','数学科学学院','物理科学与技术学院','化学化工学院','固体表面物理化学国家重点实验室','能源材料化学协同创新中心','信息科学与技术学院','软件学院','材料学院','能源学院','建筑与土木工程学院','萨本栋微米纳米科学技术研究院','醇醚酯化工清洁生产国家工程实验室',
	# 		'厦门大学生物仿生及软物质研究院','航空航天学院','生命科学学院','公共卫生学院','药学院','医学院','细胞应激生物学国家重点实验室','分子疫苗学和分子诊断学国家重点实验室','国家传染病诊断试剂与疫苗工程技术研究中心','生物医学研究院','附属中山医院','附属第一医院','附属东南医院','附属东方医院','附属厦门眼科中心','附属成功医院','附属福州二院','附属翔安医院',
	# 		'附属心血管病医院','厦大实验动物中心','细胞生物学协同创新中心','海洋与地球学院','环境与生态学院','海洋与海岸带发展研究院','近海海洋环境科学国家重点实验室']

@csrf_exempt
def AppointmentSubmit(request):
	if request.POST:
		form = {}
		form['StudentNum'] = request.POST.get('StudentNum')
		form['School'] = request.POST.get('School')
		form['AppointmentDate'] = request.POST.get('AppointmentDate')
		form['DateID'] = request.POST.get('DateID')
		form['Content'] = request.POST.get('Content')
		form['Name'] = request.POST.get('Name')
		form['MobilePhone'] = request.POST.get('MobilePhone')
		form['UserQQ'] = request.POST.get('UserQQ')
		if request.session.has_key('UserID'):
			form['UserID'] = request.session.get('UserID')
		else:
			form['UserID'] = 'unknown'
		callback = checkValidation(form)
		return HttpResponse(json.dumps(callback))

def checkValidation(form):
	try:
		appointment = Appointment.objects.get(StudentNum = form['StudentNum'], InQueue = 1)
	except:
		date = AvailableDate.objects.get(DateID = form['DateID'])
		if date.Number == date.Limit:
			return '该时段人数已满'
		else:
			date.Number = date.Number + 1
			date.save()
			try:
				Appointment(AppointmentID = str(int(time.time())), Name = form['Name'], MobilePhone = form['MobilePhone'], UserQQ = form['UserQQ'], Detail = form['Content'], StudentNum = form['StudentNum'], SequenceNumber = date.Number, UserID = form['UserID'], AppointmentDate = form['AppointmentDate'],
					School = form['School'], DateID = form['DateID'], StaffID = '110').save()
			except Exception,e:
				print Exception,":",e
				return str(e)
			return 'done' + str(date.Number)
	else:
		return '同一学号不能多次预约！'

@csrf_exempt
def AddTime(request):
	if not request.session.has_key('UserID'):
		return HttpResponse(json.dumps('notLogin'))
	if request.POST:
		DateID = str(int(time.time())) + '_' + request.session.get('UserID')
		StartTime = request.POST.get('StartTime')
		EndTime = request.POST.get('EndTime')
		Limit = request.POST.get('Limit')
		activityAbstract = request.POST.get('activityAbstract')
		AvailableDate(activityAbstract = activityAbstract, DateID = DateID, StartTime = StartTime, EndTime = EndTime, Limit = Limit).save()
		return HttpResponse(json.dumps(DateID))
	return HttpResponse('Whoops!')

@csrf_exempt
def DeleteTime(request):
	if not request.session.has_key('UserID'):
		return HttpResponse(json.dumps('notLogin'))
	if request.POST:
		DateID = request.POST.get('DateID')
		try:
			Appointment.objects.filter(DateID = DateID).delete()
			AvailableDate.objects.get(DateID = DateID).delete()
		finally:
			return HttpResponse(json.dumps('done'))
	return HttpResponse('Whoops!')

@csrf_exempt
def FinishActivity(request):
	if not request.session.has_key('UserID'):
		return HttpResponse(json.dumps('notLogin'))
	if request.POST:
		DateID = request.POST.get('DateID')
		try:
			a = AvailableDate.objects.get(DateID = DateID)
			a.IsFinished = 1;
			a.save()
		finally:
			appointments = Appointment.objects.filter(DateID = a.DateID)
			for appointment in appointments:
				appointment.InQueue = 0
				appointment.Done = 1
				appointment.save()
			return HttpResponse(json.dumps('done'))
	return HttpResponse('Whoops!')

@csrf_exempt
def FinishAppointment(request):
	if not request.session.has_key('UserID'):
		return HttpResponse(json.dumps('notLogin'))
	if request.POST:
		StudentNum = request.POST.get('StudentNum')
		try:
			a = Appointment.objects.get(StudentNum = StudentNum, InQueue = 1)
			a.Done = 1
			a.InQueue = 0
			a.save()
		except:
			return HttpResponse(json.dumps('error'))
		else:
			return HttpResponse(json.dumps('done'))
	return HttpResponse('Whoops!')

@csrf_exempt
def UpdateAvatar(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/accounts/Login/')
	if request.POST:
		f = request.POST['imgBase64']
		file_name = "static/upload/" + request.session.get('UserID')
		try:
			des = open(file_name, "w+")
			des.write(f)
			des.close()
		except Exception, e:
			print e
			raise Http404
		else:
			return HttpResponse(json.dumps("ok"))
	return HttpResponse('Whoops!')

@csrf_exempt
def AcceptAnswer(request):
	if not request.session.has_key('UserID'):
		return HttpResponse(json.dumps('notLogin'))
	if request.POST:
		AnswerID = request.POST.get('AnswerID')
		try:
			Answer = QuestionAnswers.objects.get(AnswerID = AnswerID)
			Question = QuestionList.objects.get(QuestionID = Answer.QuestionID)
		except Exception as e:
			return HttpResponse(json.dumps(e))
		Question.AcceptedAnswerID = AnswerID
		Answer.IsAccepted = 1
		Question.save()
		Answer.save()
		return HttpResponse(json.dumps('ok'))
	return HttpResponse('Whoops!')

def SetPriority(request):
	if not request.session.has_key('UserID'):
		return HttpResponse(json.dumps('notLogin'))
	if request.GET:
		NewsID = request.GET.get('NewsID')
		try:
			News = News.objects.get(NewsID = NewsID)
		except Exception as e:
			return HttpResponse(json.dumps(e))
		News.Priority = 1;
		News.save()
		return HttpResponse(json.dumps('ok'))
	return HttpResponse('Whoops!')
